package utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Properties;

/**
 * rabbitMQ工具类
 * 获取连接对象
 * 关闭通道和连接
 */

public class RabbitMQUtils {

    private static ConnectionFactory connectionFactory;
    private static Properties properties;

    static {
        // 重量级资源 类加载器只执行一次
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.11.38");
        connectionFactory.setPort(5673);
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
    }

    /**
     * 定义提供连接对象的方法
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        try {
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭通道和关闭连接工具方法
     *
     * @param channel    通道
     * @param connection 连接
     */
    public static void closeConnectionAndChannel(Channel channel, Connection connection) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
